##########################################################################################

library(data.table)
library(optparse)

##########################################################################################

option_list <- list(
    make_option(c("--sample_list_file"), type = "character"),
    make_option(c("--rsem_path"), type = "character"),
    make_option(c("--out_file"), type = "character")
)

if(1!=1){
    
    sample_list_file <- "/public/home/xxf2019/20220913_NextFlow_RNA_test/config/patients.csv"
    rsem_path <- "/public/home/xxf2019/20220913_NextFlow_RNA_test/results/RSEM"
    out_file <- "/public/home/xxf2019/20220913_NextFlow_RNA_test/results/CombineCounts.tsv"

}

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

sample_list_file <- opt$sample_list_file
rsem_path <- opt$rsem_path
out_file <- opt$out_file

##########################################################################################

dat_sample <- data.frame(fread(sample_list_file))

dat <- data.frame()
for(sample in dat_sample$sample){

    file <- paste0(rsem_path , "/" , sample , ".rsem.genes.results")
    tmp_dat <- fread(file)[,c("gene_id" , "expected_count")]
    colnames(tmp_dat)[2] <- sample

    if(nrow(dat) > 0){
        dat <- merge( dat , tmp_dat )
    }else{
        dat <- tmp_dat
    }
}

write.table( dat , out_file , row.names = F , sep = "\t" , quote = F )